<template>
  <div class="table-wrap">
    <div class="form-header">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-input
            v-model="formInline.user"
            placeholder="输入名称/编号/其他搜索"
            clearable
          />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="formInline.region"
            placeholder="输入材料商名称搜索"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增匹配</el-button>
          <el-button type="warning">批量删除</el-button>
        </el-form-item>
      </el-form>
      <div class="operate-btn-wrap">
        <el-button type="primary">类别筛选</el-button>
        <el-button type="primary">批量导入</el-button>
        <el-button type="primary">导出Excel</el-button>
      </div>
    </div>
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55">
        <template #default="scope">
          {{ getIndex(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in tableHeader"
        :key="item"
        :prop="item.prop"
        :label="item.name"
      >
        <template
          v-if="item.prop == 'fm' || item.prop == 'su'"
          #default="scope"
        >
          <img
            :src="scope.row[item.prop]"
            style="width: 80px; height: 60px"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button @click="copyRow(scope.row)" link type="primary"
            >复制</el-button
          >
          <el-button @click="handleEdit(scope.row)" link type="primary"
            >编辑</el-button
          >
          <el-button @click="handleDelete(scope.row)" link type="primary"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
        ><template v-for="(item, index) in tableHeader" :key="index">
          <el-form-item
            v-if="!item.hidden"
            :label="item.name"
            :prop="item.prop"
          >
            <el-select
              :filterable="item.filterable ? item.filterable : false"
              v-if="item.type == 'select' && !item.hidden"
              :multiple="item.multi ? true : false"
              v-model="ruleForm[item.prop]"
              placeholder=""
            >
              <el-option
                v-for="key in item.options"
                :key="key.id"
                :label="key.name"
                :value="key.id"
              />
            </el-select>
            <el-input
              v-if="item.type == 'input'"
              placeholder="请输入"
              v-model="ruleForm[item.prop]"
            ></el-input>
            <el-upload
              v-if="item.type == 'uploadImg'"
              v-model:file-list="fileList"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
            <NumberRange
              :value="ruleForm[item.prop]"
              v-if="item.type == 'numberRange'"
            ></NumberRange>
            <el-cascader
              v-if="item.type == 'cascader'"
              v-model="ruleForm[item.prop]"
              :options="item.options"
              :props="casdarProps"
              @change="handleChange"
            />

            <!-- <el-cascader
              v-if="item.type == 'cascader'"
              v-model="ruleForm[item.prop]"
              :options="item.options"
              :props="casdarProps"
              @change="handleChange"
            /> -->
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmForm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, nextTick } from "vue";
import NumberRange from "@/components/InputNumberRange";
import {
  getMatchInfos,
  addMatchInfo,
  modifyMatchInfo,
  deleteMatchInfo,
  getMatchInfo,
} from "@/api/match";
import { allMaterialCategoryInfo } from "@/api/material.js";
import { getMaterialSelectInfos } from "@/api/level-third.js";
import {
  buildingTypeInfos,
  allBuildingTypeInfo,
  colorInfos,
  gradeInfos,
  usedPartInfos,
} from "@/api/building-type.js";
import { ElMessage, ElMessageBox } from "element-plus";
const formInline = reactive({
  user: "",
  region: "",
  date: "",
});
const props = defineProps({
  buildingTypeInfoId: {
    type: Number,
    required: true,
  },
});
const casdarProps = {
  value: "buildingTypeInfoId",
  label: "buildingTypeName",
  checkStrictly: true,
};
const multipleTableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const getMatchInfoDetail = async (id) => {
  try {
    const res = await getMatchInfo(id);
    if (res.code == 200) {
      console.log("res", res);
    }
  } catch (error) {}
};

const currentPage = ref(1);
const pageSize = ref(10);
const tableHeader = ref([
  {
    prop: "buildingTypeName",
    name: "建筑大类",
    type: "select",
    hidden: true,
    options: computed(() => FormBuildingTypes.value),
  },
  // { prop: "gjfl", name: "公建分类", type: "select", hidden: true, options: [] },
  {
    prop: "colorName",
    name: "颜色",
    type: "select",

    options: computed(() => allColorInfoData.value),
  },
  {
    prop: "gradeName",
    name: "档次",
    type: "select",

    options: computed(() => allGradeInfoData.value),
  },
  {
    prop: "usedPartName",
    name: "使用部位",
    type: "select",
    options: computed(() => allUsedPartInfoData.value),
  },
  { prop: "recommendationIndex", name: "推荐系数", type: "input" },
  {
    prop: "materialCategoryName",
    name: "材料大类",
    type: "select",
    options: [],
    hidden: true,
  },
  {
    prop: "primaryMaterialName",
    name: "一级材料",
    type: "select",
    options: [],
    hidden: true,
  },
  {
    prop: "secondaryMaterialName",
    name: "二级材料",
    type: "select",
    options: [],
    hidden: true,
  },
  {
    prop: "buildingTypeName",
    name: "建筑类型",
    type: "cascader",
    options: computed(() => allBuildingTypeInfoData.value),
  },
  {
    prop: "materialName",
    name: "三级材料",
    type: "select",
    filterable: true,
    options: computed(() => FormBuildingTypes.value),
  },
]);
// 建筑类型下拉框数据
const allBuildingTypeInfoData = ref([]);

const getAllBuildingTypeInfo = async () => {
  try {
    const res = await allBuildingTypeInfo();
    if (res.code == 200) {
      allBuildingTypeInfoData.value = res.result || [];
    }
  } catch (error) {
    console.log("error", error);
  }
};
getAllBuildingTypeInfo();
// 颜色列表下拉框数据
const allColorInfoData = ref([]);
const getAllColorInfos = async () => {
  try {
    const res = await colorInfos();
    if (res.code == 200) {
      allColorInfoData.value =
        res.result.list.map((x) => {
          return { id: x.colorInfoId, name: x.colorName };
        }) || [];
    }
  } catch (error) {
    console.log("error", error);
  }
};
getAllColorInfos();
// 档次列表下拉框数据
const allGradeInfoData = ref([]);
const getAllGradeInfos = async () => {
  try {
    const res = await gradeInfos();
    if (res.code == 200) {
      allGradeInfoData.value =
        res.result.list.map((x) => {
          return { id: x.gradeInfoId, name: x.gradeName };
        }) || [];
    }
  } catch (error) {
    console.log("error", error);
  }
};
getAllGradeInfos();
// 使用部位列表下拉框数据
const allUsedPartInfoData = ref([]);
const getAllUsedPartInfos = async () => {
  try {
    const res = await usedPartInfos();
    if (res.code == 200) {
      allUsedPartInfoData.value =
        res.result.map((x) => {
          return { id: x.buildingTypeInfoId, name: x.buildingTypeName };
        }) || [];
    }
  } catch (error) {
    console.log("error", error);
  }
};
getAllUsedPartInfos();
// 三级材料列表下拉框数据
const FormBuildingTypes = ref([]);
const getFormBuildingTypes = async () => {
  try {
    const params = { count: false };
    const res = await getMaterialSelectInfos(params);
    if (res.code == 200) {
      FormBuildingTypes.value =
        res.result.map((x) => {
          return { id: x.materialInfoId, name: x.materialName };
        }) || [];
    }
  } catch (error) {}
};
getFormBuildingTypes();
const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};
const dialogTitle = ref("添加匹配");
const dialogType = ref("add");
const dialogVisible = ref(false);
const currentRow = ref({});
const handleEdit = (item) => {
  dialogTitle.value = "编辑匹配";
  dialogType.value = "edit";
  dialogVisible.value = true;
  currentRow.value = item;
  console.log("item", item);
  // getMatchInfoDetail(item.matchInfoId);
  nextTick(() => {
    ruleForm.colorName = item.colorInfoId;
    ruleForm.gradeName = item.gradeInfoId;
    ruleForm.usedPartName = item.usedPartInfoId;
    ruleForm.recommendationIndex = item.recommendationIndex;
    ruleForm.buildingTypeName = item.buildingTypeInfoId;
    ruleForm.materialName = item.materialInfoId;
  });
};

const handleDelete = (item) => {
  ElMessageBox.confirm("确认删除此匹配信息?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteMatchInfo({
        matchInfoId: item.matchInfoId,
        recordVersion: item.recordVersion,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getMatchList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
const AllMaterialCasdar = ref([]);
const getAllMaterialCasdar = async () => {
  const res = await allMaterialCategoryInfo();
  AllMaterialCasdar.value = res.result || [];
};
const getAllTypeInfo = async () => {};
const copyRow = (item) => {
  currentRow.value = item;
  console.log("item", item);
  ElMessage({
    type: "success",
    message: "复制成功",
  });
  setTimeout(() => {
    dialogTitle.value = "添加匹配";
    dialogType.value = "add";
    dialogVisible.value = true;
    nextTick(() => {
      ruleForm.colorName = item.colorInfoId;
      ruleForm.gradeName = item.gradeInfoId;
      ruleForm.usedPartName = item.usedPartInfoId;
      ruleForm.recommendationIndex = item.recommendationIndex;
      ruleForm.buildingTypeName = item.buildingTypeInfoId;
      ruleForm.materialName = item.materialInfoId;
    });
  }, 1000);
};
const handleAdd = () => {
  dialogTitle.value = "添加匹配";
  dialogType.value = "add";
  dialogVisible.value = true;
  nextTick(() => {
    ruleFormRef.value.resetFields();
  });
};
const tableData = ref([]);
const getMatchList = async () => {
  try {
    const params = {
      count: true,
      pageId: 1,
      pageSize: 20,
      buildingTypeInfoId: props.buildingTypeInfoId,
    };
    const res = await getMatchInfos(params);
    if (res.code == 200) {
      tableData.value = res.result.list || [];
    }
  } catch (error) {
    console.log("error", error);
  }
};
getMatchList();
const onSubmit = () => {};
const ruleFormRef = ref();
const ruleForm = reactive({
  buildingTypeName: "",
  colorName: [],
  gradeName: [],
  usedPartName: "",
  recommendationIndex: "",
  materialCategoryName: [],
});
const rules = reactive({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  region: [
    {
      required: true,
      message: "Please select Activity zone",
      trigger: "change",
    },
  ],
  count: [
    {
      required: true,
      message: "Please select Activity count",
      trigger: "change",
    },
  ],
  date1: [
    {
      type: "date",
      required: true,
      message: "Please pick a date",
      trigger: "change",
    },
  ],
  date2: [
    {
      type: "date",
      required: true,
      message: "Please pick a time",
      trigger: "change",
    },
  ],
  type: [
    {
      type: "array",
      required: true,
      message: "Please select at least one activity type",
      trigger: "change",
    },
  ],
  resource: [
    {
      required: true,
      message: "Please select activity resource",
      trigger: "change",
    },
  ],
  desc: [
    { required: true, message: "Please input activity form", trigger: "blur" },
  ],
});
const confirmForm = async () => {
  console.log("confirm", ruleForm);
  let buildingTypeInfoId = "";
  if (Array.isArray(ruleForm.buildingTypeName)) {
    buildingTypeInfoId =
      ruleForm.buildingTypeName && ruleForm.buildingTypeName.length > 0
        ? Number(ruleForm.buildingTypeName.slice(-1))
        : "";
  } else {
    buildingTypeInfoId = ruleForm.buildingTypeName;
  }

  const colorInfoId = ruleForm.colorName;
  const gradeInfoId = ruleForm.gradeName;
  const materialInfoId = ruleForm.materialName;
  const usedPartInfoId = ruleForm.usedPartName;
  const recommendationIndex = ruleForm.recommendationIndex;
  const temp = {
    buildingTypeInfoId,
    colorInfoId,
    gradeInfoId,
    materialInfoId,
    usedPartInfoId,
    recommendationIndex,
  };
  if (dialogType.value == "add") {
    const res = await addMatchInfo(temp);
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      dialogVisible.value = false;
      getMatchList();
    }
  } else {
    const param = {
      ...temp,
      matchInfoId: currentRow.value.matchInfoId,
      buildingTypeInfoId: currentRow.value.buildingTypeInfoId,
      recordVersion: currentRow.value.recordVersion,
    };
    const res = await modifyMatchInfo(param);
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      dialogVisible.value = false;
      getMatchList();
    }
  }
};
</script>
<style lang="scss" scoped>
.table-wrap {
  padding: 20px;
  .form-header {
    display: flex;
    justify-content: space-between;
  }
}
.demo-ruleForm {
  width: 100%;
  .el-select {
    width: 100%;
  }
}
</style>
